<template>
    <div class="main">
        <!-- 面包屑 -->
        <!-- <div class="breadcrumb">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/' }">Home</el-breadcrumb-item>
                <el-breadcrumb-item>UserGroupManagement</el-breadcrumb-item>
                <el-breadcrumb-item>UserGroupList</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="addUersGroup fl">
           <el-input placeholder="Please enter the content" v-model="searchVal" class="search-input" @keydown.enter.native="handleSearch" @input="handleData">
                <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
            <el-button type="primary" plain @click="handleAdd">AddUserGroup</el-button>
        </div> -->
        <!-- 表格 -->
         <el-table
            :data="tableData"
            border
            style="width: 100%;"
            default-expand-all
            >
            <el-table-column
              type="expand"
              width="60"
            >
             <!-- <div style="margin:8px;">
                <el-tree
                :data="rightsData"
                show-checkbox
                default-expand-all
                highlight-current
                node-key="id"
                ref="tree"
                :props="defaultProps">
              </el-tree>
             </div> -->
               <template slot-scope="props">
                  <div>
                    <el-checkbox 
                      :indeterminate="props.row.isIndeterminate" 
                      v-model="props.row.checkAll" 
                      @change="handleCheckAllChange(props.row)"
                      >全选12
                    
                    </el-checkbox>
                    
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group 
                      v-model="props.row.checkedRights" 
                      @change="handleCheckedCitiesChange(props.row)" >
                      <el-checkbox v-for="right in props.row.rights" :label="right" :key="right">{{right}}</el-checkbox>
                    </el-checkbox-group>
                    </div>
                  
              </template>
            </el-table-column>

            <el-table-column
                type="index"
                width="50"
                >
            </el-table-column>
            <el-table-column
                prop="groupname"
                label="UserGroupName"
                width="180"
                >
            </el-table-column>
            <!-- <el-table-column
                prop="groupmembers"
                label="UserGroupMembers"
                width="320"
                >
            </el-table-column> -->
            <el-table-column
                prop="creationTime"
                label="CreationDate"
                >
            </el-table-column>
            <el-table-column
                label="Operation"
                >
                <template slot-scope="scope">
                <!--  点击编辑按钮 -->
                <el-button
                    type="primary"
                    icon="el-icon-edit"
                    @click="handleEdit(scope.row)"
                    size="mini">Edit123</el-button>
                    <!-- scope.row获取到的是你点击的那一行对象的所有数据 -->
                <el-button
                    icon="el-icon-delete"
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.row)"
                    id="delete"
                    :disabled="scope.row._id=='Q8JKdJj2furggT2uv'"
                    >Delete</el-button>
                </template>
            </el-table-column>
        </el-table>
    <!-- 添加用户组对话框 -->
    
    <el-dialog title="AddUserGroup" :visible.sync="AddDialogVisible" width="40%" height="40%" class="addGroup">
      <el-form :model="addForm" ref="addRef" :rules="myrules">
        <el-form-item label="UserGroupName" label-width="160px" prop="groupname" label-height="100px">
          <el-input v-model="addForm.groupname" autocomplete="off"></el-input>
        </el-form-item>

        <!-- <el-form-item label="UserGroupMembers" label-width="160px" prop="groupmembers"> -->
          <!-- <el-input v-model="addForm.groupmembers" autocomplete="off"></el-input> -->
           <!-- <el-select v-model="usersVal" multiple placeholder="请选择" >
            <el-option
              v-for="item in options"
              :key="item._id"
              :label="item.username"
              :value="item._id">
            </el-option>
          </el-select>
        </el-form-item> -->
        
      </el-form>
      <div slot="footer">
        <el-button @click="AddDialogVisible = false" >Cancel</el-button>
        <el-button type="primary" @click="confirmAdd" >Confirm</el-button>
      </div>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog title="EditingUserGroups" :visible.sync="EditDialogVisible" width="40%" height="40%" class="editDialog">
      <!-- 3.1 在el-form组件上添加rules属性 -->
      <el-form :model="editForm" ref="addRef" :rules="myrules">
        <el-form-item label="UserGroupName" label-width="160px" prop="groupname">
          <el-input v-model="editForm.groupname" autocomplete="off"  @keyup.enter.native="confirmEdit"></el-input>
        </el-form-item>
        <!-- <el-form-item label="UserGroupMembers" label-width="160px" prop="groupmembers">
          <el-input v-model="editForm.groupmembers"  autocomplete="off"></el-input>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="btn">
        <el-button @click="EditDialogVisible = false" >Cancel</el-button>
        <el-button type="primary" @click="confirmEdit" >Confirm</el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
      <!-- <div class="pagination">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
          :total="totalNum"
          :current-page="currentPage"
          :page-size="pageSize">
        </el-pagination>
      </div> -->
    </div>
</template>
<script>
import {Meteor} from 'meteor/meteor';
import {UserGroup,Right} from '/imports/collections/collection'
// const cityOptions = ['管理员', '普通用户1', '普通用户2', '普通用户3'];
export default {
    data() {
      return {
        editData:{},
        tableData: [],     //表格数据
        // usersDate:[],      //用户组成员数据
        currentRow: null,
        AddDialogVisible: false,    //添加对话框的默认状态
        EditDialogVisible:false,    //编辑对话框默认状态
        totalNum:0,     //数据总条数，默认为0
        currentPage:1,    //默认展示第一页
        pageSize:6 ,       //页面显示的数据条数
        pageNum:1,         //当前页码默认为1
        searchVal:'',
        addForm:{
            groupname:''
        },
        editForm:{
            groupname:'',
            // groupmembers:'',
            _id:''
        },
        myrules:{                   //对表单进行校验
            groupname: [
                { required: true, message: 'Please enter the usergroupname', trigger: 'blur' }
                ],
                groupmembers: [
                { required: true, message: 'Please select the groupmembers', trigger: 'blur' }
                ]                    
        },
        // 权限复选框
          // checkAll: false,
          // checkedRights: [],
          // rightOptions: [],
          // isIndeterminate: true,
          val:false
        // 选择器
        // options: [],
        // usersVal: [],
      }
    },
    mounted () {
      var that=this;
      var timeout=setTimeout(function(){
            that.initPage();
        },500)
    },
    methods:{
      // 当清空搜索框中的内容时，重新将数据请求回来
      handleData(){
        this.initPage();
      },
     
      // 封装时间戳的转换
      dateFormat(time){
         // 时间戳转换 
                let date = new Date(time + 8 * 3600000);
                let str = date.toISOString().replace('T',' ');
                return str.substr(0, str.lastIndexOf('.'));
      },
        handleCurrentChange(val) {
        this.currentRow = val;
      },
    //   点击添加用户组按钮
    handleAdd(){
        this.AddDialogVisible=true;
        this.$nextTick(() => {
            // 对表单进行重置并移除所有的校验结果
        this.$refs.addRef.resetFields();
      })
      // 用户组成员需要在用户表中获取，将成员显示出来
    // var users=Meteor.users.find().fetch();
    //  for(var i=0;i<users.length;i++){
    //    this.options.push(users[i])
    //  }
    },
    //   点击编辑按钮
    handleEdit(row){
      // console.log(row);
      // alert(1)
        this.EditDialogVisible=true;
        this.editForm.groupname=row.groupname;
        // this.editForm.groupmembers=row.groupmembers;
        this.editForm._id=row._id;
        this.editData.groupname=row.groupname;
        // this.editData.groupmembers=row.groupmembers;
        this.editData._id=row._id;
    },
    // 点击删除按钮
    handleDelete(row){
        this.$confirm('This action will permanently delete the usergroup. Do you want to continue?', 'Tips', {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          UserGroup.remove({'_id':row._id});
           if(this.pageNum>1){
                this.handleCurrentChange(this.pageNum)
              }else{
                this.initPage();
              }
          this.$message({
            type: 'success',
            message: 'Successful deletion!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: 'Canceled deletion'
          });          
        });
    },
    // 对话框的关闭状态
     handleClose(done) {
        this.$confirm('Confirm closure?')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
    //   添加确认按钮
    confirmAdd(){
        this.AddDialogVisible=false;
        // 校验通过
        this.$refs.addRef.validate(isPass=>{
          if(isPass){
            this.addForm.date=this.dateFormat(Date.now());
            // 添加操作
            // this.tableData.push(this.addForm);
            var addGroup={
              'groupname':this.addForm.groupname,
              'creationTime':this.addForm.date,
              'permissionName':''
            }
            UserGroup.insert(addGroup)

            this.initPage()
          }
        })
        
    },
    // 编辑确认按钮
    confirmEdit(){
        this.EditDialogVisible=false;
        var id=this.editData._id;
        var editGroup={
          'groupname':this.editForm.groupname,
          // 'groupmembers':this.editForm.groupmembers,
          'creationTime':this.dateFormat(Date.now())
        }
        UserGroup.update({'_id':id},editGroup);
        this.initPage();
    },
    handleCurrentChange(val) {
        // console.log(`当前页: ${val}`);
        this.tableData=[]
        this.pageNum=val;
        var UserGroupData=UserGroupList.find().fetch();
        if(val!==1){
            // 13-(val-1)*6  (val-1)*6+1  2:7 13 | 3:13  18 |  4: 19 20
            for(var i=(val-1)*this.pageSize;i<(val*this.pageSize+1) && (UserGroupData.length);i++){
                this.tableData.push(UserGroupData[i])
            }
            if((val*this.pageSize+1)>UserGroupData.length){
                this.tableData=[];
                for(var i=(val-1)*this.pageSize;i<(UserGroupData.length);i++){
                this.tableData.push(UserGroupData[i])
            }
            }
        }else if(val==1){
            this.initPage();
        }
    },
    // 搜索框事件
    handleSearch(){
      this.pageNum=1;
          var id=[];
          for(var i=0;i<UserGroup.find().count();i++){
            if(UserGroup.find().fetch()[i].groupname.indexOf(this.searchVal.trim())!=-1){
              id.push(UserGroup.find().fetch()[i]._id)
            }
          }
          var newTableData=[]
        // 循环找出要查找的对象
          for(var i=0;i<this.tableData.length;i++){
              for(var j=0;j<id.length;j++){
                if(this.tableData[i]._id===id[j]){
                  newTableData.push(this.tableData[i])
                }
              }
          }
          this.tableData=[]
          // console.log(newTableData)
          for(var j=0;j<newTableData.length;j++){
              this.tableData.push(newTableData[j]);
          }
       
    },
     
      // 初始化表格数据
      initPage(){
       
        // this.tableData=UserGroup.find({}).fetch()
        this.tableData=[];
        this.totalNum=UserGroup.find().count();
        var UserGroupData=UserGroup.find().fetch();
        var rightsData=Right.find().fetch();

        for(var i=0;i<UserGroupData.length;i++){
            if(i<this.pageSize){
                this.tableData.push(UserGroupData[i])
            }
        }
        var rights=[]
        for(var i=0;i<rightsData.length;i++){
          rights.push(rightsData[i].permissionName)
        }

        for(var j=0;j<this.tableData.length;j++){
          this.tableData[j].rights=rights;
          this.tableData[j].checkAll=false;
          this.tableData[j].isIndeterminate=true;
          this.tableData[j].checkedRights=[];
          // this.tableData[j].rights.push(rights)
        }
         
        // console.log("tableData:"+JSON.stringify( this.tableData))

          // 这是添加框中有用户选项
          // var users=Meteor.users.find().fetch()
          // for(var i=0;i<UserGroupData.length;i++){
          //   this.usersDate=[]
          //   this.tableData.push(UserGroupData[i])
          //   for(var j=0;j<users.length;j++){
          //     if(UserGroupData[i].groupname===users[j].groupName){
          //       // this.tableData[i].groupmembers=users[j].username;
          //       this.usersDate.push(users[j].username+",")
          //     }
          //   }
          //     // this.usersDate.delete()
          //    this.tableData[i].groupmembers=this.usersDate
          // }



        // UserGroup.insert({
        //   groupname:"test02",
        //   creationTime:this.dateFormat(Date.now())
        // })

     
      // console.log("this.rightjjj:"+JSON.stringify(rightsData))
       console.log("row:"+this.tableData)
      },
      
      // 权限复选框
      // checkedRights可以获取到被选的复选框
      // 全选框
       handleCheckAllChange(row) {
        //  console.log("checkAllrow:"+JSON.stringify(row))
        this.val=!this.val;
        row.checkedRights = this.val ? row.rights : [];
        row.isIndeterminate = false;
         var newRight={
          'groupname':row.groupname,
          'creationTime':row.creationTime,
          'permissionName':row.checkedRights
        }
        // console.log("this.checkRights:"+this.checkedRights)
        // UserGroup.update({'_id':row._id},newRight)
        },
        // 单个复选框
        handleCheckedCitiesChange(row) {
          console.log("checkedRights:",row)
          // // console.log("value:"+value.length)
          let checkedCount = row.checkedRights.length;
          row.checkAll = checkedCount === row.rights.length;
          row.isIndeterminate = checkedCount > 0 && checkedCount < row.rights.length;
           var newRight={
          'groupname':row.groupname,
          'creationTime':row.creationTime,
          'permissionName':row.checkedRights
        }
        // UserGroup.update({'_id':row._id},newRight)
        }
    }
    
    
}
</script>
<style lang="scss" scope>
    .main{
        .breadcrumb{
            background-color: #fff;
            height:30px;
            .el-breadcrumb{
                line-height: 30px;
                font-size: 14px;
                padding-left: 10px;
            }
        }
        .el-table__header tr,
        .el-table__header th {
          padding: 0;
          height: 70px;
          line-height: 70px;
          color: #333;
      }
      .el-table__body tr,
      .el-table__body td {
          padding: 0;
          height: 50px;
      }
      
    }
    .addUersGroup{
        margin-top: -45px;
        height: 115px;
    }
    .has-gutter{
        height: 100px;
    }
    
    .pagination{
        .el-pagination {
            margin-top: 20px;
        }
    }
    .addGroup{
        .el-dialog{
          line-height: 0;
        }
        .el-dialog__wrapper{
            .el-dialog{
                .el-dialog__footer{
                    height: 120px;
                }
            }
        }
        .btn{
        margin-top: -60px;
        }
    }
    .editDialog{
      .el-dialog{
          line-height: 0;
        }
    }

    .el-select{
      width: 340px;
    }
    .main .el-table__body tr, .main .el-table__body td {
    line-height: 30px;
    padding-left: 20px;
    }
</style>

